package presentationTier.actions;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFileChooser;
import presentationTier.Global;
import presentationTier.MainForm;
import presentationTier.MovieTableModel;

/**
 *
 * @author vojta
 */
public class ExportToXMLAction implements ActionListener{

    MainForm form;

    public ExportToXMLAction(MainForm aThis) {
        form = aThis;
    }

    public void actionPerformed(ActionEvent e) {
        MovieTableModel model = (MovieTableModel) form.jTable1.getModel();

        JFileChooser fc = new JFileChooser();
        fc.setSelectedFile(new File(".xml"));
        int ret = fc.showSaveDialog(fc);
        String path = "";
        String file = "";
        String completePath = "";
        if (ret == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile().getName().toString();
            path = fc.getSelectedFile().getParent().toString();            
            completePath = path + "/" + file;
            //JOptionPane.showMessageDialog(form, completePath);

        }

        String xml = Global.XML_HEADER;

        for (int i = 0; i < model.getRowCount(); i++) {
            xml += model.getMovieAt(i).toXML();
        }
        xml += "</movies>";
        
        try {
            FileWriter fw = new FileWriter(completePath);
            fw.write(xml);
            fw.close();
        } catch (IOException ex) {
            form.error(ex);
        }
    }

}
